package com.wfm.mianshi.生产消费模型;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class 利用线程安全队列 {
    // 生产者类
    static class ProducerUsingQueue implements Runnable {
        private final BlockingQueue<Integer> queue;

        public ProducerUsingQueue(BlockingQueue<Integer> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                for (int i = 0; i < 10; i++) {
                    // 将元素放入队列，如果队列满了会阻塞
                    queue.put(i);
                    System.out.println("生产者生产: " + i);
                    Thread.sleep(100);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    // 消费者类
    static class ConsumerUsingQueue implements Runnable {
        private final BlockingQueue<Integer> queue;

        public ConsumerUsingQueue(BlockingQueue<Integer> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                for (int i = 0; i < 10; i++) {
                    // 从队列中取出元素，如果队列为空会阻塞
                    Integer item = queue.take();
                    System.out.println("消费者消费: " + item);
                    Thread.sleep(200);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    public static void main(String[] args) {
        // 创建一个容量为 5 的线程安全队列
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5);

        Thread producerThread = new Thread(new ProducerUsingQueue(queue));
        Thread consumerThread = new Thread(new ConsumerUsingQueue(queue));

        producerThread.start();
        consumerThread.start();

        try {
            producerThread.join();
            consumerThread.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
